package com.studyweb.controller;

import com.studyweb.pojo.vo.Result;
import com.studyweb.service.VocabularyImportService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.ClassPathResource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import jakarta.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;

@Slf4j
@RestController
@RequestMapping("/api/vocabulary")
public class VocabularyImportController {

    @Autowired
    private VocabularyImportService vocabularyImportService;

    @PostMapping("/import")
    public Result<?> importVocabulary(
            @RequestParam("file") MultipartFile file,

            HttpServletRequest request) {
        try {
            // 从拦截器设置的request attribute中获取用户ID
            Long userId = (Long) request.getAttribute("userId");
            int importedCount = vocabularyImportService.importVocabularyFromExcel(file, userId);
            return Result.success("词语导入成功", importedCount);
        } catch (Exception e) {
            log.error("导入词语失败: {}", e.getMessage(), e);
            return Result.error("导入失败: " + e.getMessage());
        }
    }

    @GetMapping("/downloadTemplate")
    public ResponseEntity<byte[]> downloadTemplate() {
        try {
            ClassPathResource resource = new ClassPathResource("templates/vocabulary_import_template.xlsx");
            byte[] templateBytes = resource.getInputStream().readAllBytes();

            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.parseMediaType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"));
            
            // 使用 RFC 5987 编码格式处理中文文件名
            String encodedFilename = "filename*=UTF-8''" + URLEncoder.encode("词语导入模板.xlsx", StandardCharsets.UTF_8.toString()).replace("+", "%20");
            headers.add(HttpHeaders.CONTENT_DISPOSITION, "attachment; " + encodedFilename);

            return ResponseEntity.ok()
                    .headers(headers)
                    .body(templateBytes);
        } catch (IOException e) {
            log.error("下载模板失败: {}", e.getMessage(), e);
            return ResponseEntity.notFound().build();
        }
    }
}